<?php

namespace app\controllers;

use app\models\IcdNineEntries;
use app\models\IcdCodes;
use app\models\Patients;

use lithium\security\Auth;

use lithium\action\DispatchException;

class IcdNineEntriesController extends \lithium\action\Controller {

	public function index() {
		if (!Auth::check('default')) {
			return $this->redirect('Sessions::add');
		}
		$icdNineEntries = IcdNineEntries::all();
		return compact('icdNineEntries');
	}

	public function view() {
		if (!Auth::check('default')) {
			return $this->redirect('Sessions::add');
		}
		$icdNineEntry = IcdNineEntries::first($this->request->id, array(
			'with' => 'IcdCodes'
		));
		$patient = Patients::find($icdNineEntry->patient_id);
		return compact('icdNineEntry', 'patient');
	}

	public function add() {
		if (!Auth::check('default')) {
			return $this->redirect('Sessions::add');
		}

		$icdCodesCollection = IcdCodes::all(array(
			'order' => array('name' => 'ASC')
		));

		$icdNineEntry = IcdNineEntries::create();

		$patients = Patients::all(array(
			'order' => array('PatID' => 'ASC')
		));

		if (($this->request->data) && $icdNineEntry->save($this->request->data)) {
			return $this->redirect(array('IcdNineEntries::view', 'args' => array($icdNineEntry->id)));
		}
		return compact('icdNineEntry', 'icdCodesCollection', 'patients');
	}

	public function edit() {
		if (!Auth::check('default')) {
			return $this->redirect('Sessions::add');
		}

		$icdCodesCollection = IcdCodes::all(array(
			'order' => array('name' => 'ASC')
		));

		$icdNineEntry = IcdNineEntries::find('first', array(
			'conditions' => array('IcdNineEntries.id' => $this->request->args[0]),
			'with' => 'IcdCodes'
		));

		if (!$icdNineEntry) {
			return $this->redirect('IcdNineEntries::index');
		}

		$patient = Patients::find($icdNineEntry->patient_id);

		if (($this->request->data) && $icdNineEntry->save($this->request->data)) {
			return $this->redirect(array('Patients::view', 'args' => array($patient->id)));
		}
		return compact('icdNineEntry', 'patient', 'icdCodesCollection');
	}

	public function delete() {
		if (!Auth::check('default')) {
			return $this->redirect('Sessions::add');
		}
		//if (!$this->request->is('post') && !$this->request->is('delete')) {
		//	$msg = "IcdNineEntries::delete can only be called with http:post or http:delete.";
		//	throw new DispatchException($msg);
		//}
		IcdNineEntries::find($this->request->args[0])->delete();
		return $this->redirect(array('Patients::view', 'args' => array($this->request->args[1])));
	}
}

?>